<?php
namespace Modules\Activity\Http\Controllers\Admin\YiFanShang;

use Illuminate\Http\Request;
use Illuminate\Routing\Controller;

use \Modules\Activity\Entities\YiFanShang\Activity;
use \Modules\Activity\Entities\YiFanShang\Room;
// use \Modules\Activity\Entities\ActivityRecord;

use Validator;
use ThrowException;
use DB;

class ActivityController extends Controller
{
    public function index(Request $req)
    {
        $rule = [
            // 'type' => ['required']
        ];
        Validator::make($req->all(), $rule)->fails() && ThrowException::BadRequest(); 

        $options = $req->all();

        $options['order_by'] = ['list_weight' => 'desc'];
        // $options['with_count'] = ['records', 'skus'];
        // $options['with'] = ['activity_info'];

        $list = Activity::getList($options);

        $list->each(function ($item) {
            $item->normal_sku_stock = $item->normal_skus()->sum('stock');
            $item->gift_sku_stock = $item->gift_skus()->sum('stock');
            $item->open_total = $item->rooms()->sum('open_index');
        });

        return $list->generateListResponse();
    }

    public function show(Request $req, $uuid)
    {
        // 
        $item = Activity::getEntity([
            'uuid' => $uuid
        ]);

        $info = $item->getInfo();

        return [
            'info' => $info
        ];
    }

    public function store(Request $req)
    {
        $rule = [
            'room_total' =>  ['required'],
            'gift_sku_total' => ['required'],
            'normal_sku_total' => ['required']
        ];
        Validator::make($req->all(), $rule)->fails() && ThrowException::BadRequest(); 

        if ($req->room_total <= 0) {
            ThrowException::Conflict('房间数不能小于0');
        }

        if ($req->normal_sku_total <= 0) {
            ThrowException::Conflict('购买赏不能小于0');
        }

        $info = $req->all();


        DB::beginTransaction();

        $info['stock']  = 0;
        $info['status'] = 0;
        $item = Activity::create($info);

        // 创建普通赏
        $item->createSku(0, $req->normal_sku_total);
        // 创建赠送赏
        $item->createSku(1, $req->gift_sku_total);

        // 房间数量
        $roomTotal = $req->room_total;

        // 创建房间
        $item->createRoom($roomTotal);

        DB::commit();

        $item->refreshPerRoomTotal();

        return [
            'id' => $item->id,
            'uuid' => $item->uuid
        ];
    }

    public function update(Request $req, $uuid)
    {
        $rule = [
        ];
        Validator::make($req->all(), $rule)->fails() && ThrowException::BadRequest(); 

        $item = Activity::getEntity([
            'uuid' => $uuid
        ]);

        DB::beginTransaction();

        if ($req->type === 'update') {
            $info = $req->input('attributes');

            if (@$info['status'] === 1) {
                foreach ($item->gift_skus as $sku) {
                    if (!$sku->lottery_start_point || !$sku->lottery_end_point) {
                        ThrowException::Conflict('请先填写完所有隐藏款的抽取位置');
                    }
                }
            }

            $item->update($info);
        }
        if ($req->type === 'copy') {
            $item->copy();
        }

        $item->refreshPerRoomTotal();

        DB::commit();

        return [];
    }

    public function destroy(Request $req, $uuid)
    {
        $rule = [
        ];
        Validator::make($req->all(), $rule)->fails() && ThrowException::BadRequest(); 

        $item = Activity::getEntity([
            'uuid' => $uuid
        ]);

        $item->delete();

        return [];
    }

    // 用户列表
    public function userIndex(Request $req, $uuid)
    {
        $rule = [
            'type' => ['required']
        ];
        Validator::make($req->all(), $rule)->fails() && ThrowException::BadRequest(); 

        $options = $req->all();

        $activity = Activity::getEntity([
            'uuid' => $uuid
        ]);

        // if ($req->type === 'lucky') {
        //     $builder =  $activity->lucky_records(); 
        // }
        // elseif ($req->type === 'all') {
        //     $builder =  $activity->records(); 
        // }

        $list = ActivityRecord::getList([
            'builder' => $builder,
            'with' => ['user'],
            // 'with_count' => ['lottery_tickets', 'invitees'],
            'only' => [
                'id',
                'lottery_tickets_count',
                'invitees_count',
                'is_lucky_user',
                'created_at',
                'user' => [
                    'name',
                    'headimg',
                    'gender'
                ]
            ]
        ]);

        return $list->generateListResponse();
    }

    // 运行测试, 请不要在正式运营后调用此api
    // 此api会模拟多人并发抽取指定roomId房间的赏品
    public function runTest(Request $req, $uuid)
    {
        $room = Room::getEntity([
            'uuid' => $uuid
        ]);

        // 随机每次模拟1-5发
        $total = rand(1, 5);
        $user = NULL;
        $order = NULL;
        $options = [];

        $room->pickLuckySkus($total, $user,  $order, $options);

        return [];
    }
}
